package liuwanghui.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import liuwanghui.constant.CommonConstant;
import liuwanghui.constant.OrderStatusConstant;
import liuwanghui.dto.request.*;
import liuwanghui.exception.BusinessException;
import liuwanghui.mapper.OrderMapper;
import liuwanghui.pojo.Order;
import liuwanghui.pojo.Result;
import liuwanghui.service.OrderService;
import liuwanghui.util.CacheUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final CacheUtil cacheUtil;

    @Override
    public Result getOrders(OrderQueryDTO params) {
        PageHelper.startPage(params.getPage(), params.getPageSize());
        List<Order> orders = orderMapper.findOrdersBySearch(params);
        return Result.success(new PageInfo<>(orders));
    }

    @Override
    public Result getOrderDetail(Long id, Boolean includeHistory) {
        Order order = orderMapper.findOrderById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        if (Boolean.TRUE.equals(includeHistory)) {
            var history = orderMapper.findOrderStatusHistory(id);
            order.setStatusHistory(history);
        }

        return Result.success(order);
    }

    @Override
    @Transactional
    public void updateOrderStatus(Long id, OrderStatusDTO dto) {
        Order order = orderMapper.findOrderById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 检查状态变更是否合法
        if (!isValidStatusTransition(order.getStatus(), dto.getStatus())) {
            throw new BusinessException("非法的状态变更");
        }

        // 更新订单状态
        orderMapper.updateOrderStatus(id, dto.getStatus());

        // 记录状态变更日志
        OrderStatusLogDTO log = new OrderStatusLogDTO();
        log.setOrderId(id);
        log.setOldStatus(order.getStatus());
        log.setNewStatus(dto.getStatus());
        log.setOperator(dto.getOperator());
        log.setRemark(dto.getRemark());
        log.setCreateTime(LocalDateTime.now());
        orderMapper.insertOrderStatusLog(log);

        // 清除缓存
        cacheUtil.deleteByPattern(CommonConstant.CacheKey.ORDER + id);
    }

    @Override
    @Transactional
    public void cancelOrder(Long id, OrderCancelDTO dto) {
        Order order = orderMapper.findOrderById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        if (OrderStatusConstant.CANCELLED.equals(order.getStatus())) {
            throw new BusinessException("订单已取消");
        }

        // 更新订单状态为已取消
        OrderStatusDTO statusDTO = new OrderStatusDTO();
        statusDTO.setStatus(OrderStatusConstant.CANCELLED);
        statusDTO.setOperator(dto.getCancelledBy());
        statusDTO.setRemark(dto.getReason());
        updateOrderStatus(id, statusDTO);

        // 记录取消信息
        orderMapper.updateOrderCancelInfo(id, dto);
    }

    @Override
    @Transactional
    public void shipOrder(Long id, OrderShipDTO dto) {
        Order order = orderMapper.findOrderById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        if (!OrderStatusConstant.PAID.equals(order.getStatus())) {
            throw new BusinessException("订单状态不正确");
        }

        // 更新订单状态为配送中
        OrderStatusDTO statusDTO = new OrderStatusDTO();
        statusDTO.setStatus(OrderStatusConstant.SHIPPING);
        statusDTO.setOperator(dto.getOperator());
        statusDTO.setRemark("订单发货：" + dto.getShippingNumber());
        updateOrderStatus(id, statusDTO);

        // 记录发货信息
        orderMapper.updateOrderShipInfo(id, dto);
    }

    @Override
    public Result getRecentOrders(String role, Integer days, Integer limit) {
        List<Order> orders = orderMapper.findRecentOrders(role, days, limit);
        return Result.success(orders);
    }

    private boolean isValidStatusTransition(String oldStatus, String newStatus) {
        // 根据业务规则实现状态转换的合法性检查
        return switch (oldStatus) {
            case OrderStatusConstant.PENDING -> 
                newStatus.equals(OrderStatusConstant.PAID) ||
                newStatus.equals(OrderStatusConstant.CANCELLED);
            case OrderStatusConstant.PAID ->
                newStatus.equals(OrderStatusConstant.SHIPPING) ||
                newStatus.equals(OrderStatusConstant.CANCELLED);
            case OrderStatusConstant.SHIPPING ->
                newStatus.equals(OrderStatusConstant.COMPLETED);
            default -> false;
        };
    }
} 